package com.pengliu.config.logs;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;

@Aspect
@Component
public class SqlLogAspect {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Pointcut("execution(* com.pengliu.dao.*.*(..))")
    public void mapperLog() {}
 
    @Around(value = "mapperLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    	String className = joinPoint.getTarget().getClass().getName();
    	String methodName = joinPoint.getSignature().getName();
        String classMethod = className + "." + methodName + "()";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    	logger.info("-------------------------------------------------(Start -{}- Mapper)-------------------------------------------------",methodName);
    	logger.info("★mapper调用:{}\t调用时间:{}",classMethod,sdf.format(new Date()));
        Object result = joinPoint.proceed(joinPoint.getArgs());
        logger.info("★数据库返回:{}",JSON.toJSONString(result));
        logger.info("-------------------------------------------------(End -{}- Mapper)-------------------------------------------------",methodName);
        return result;
    }
    
    @AfterThrowing(pointcut = "mapperLog()", throwing = "e")
    public void doAfterThrowing(Exception e) throws Exception{
        throw new SqlException(e);
    }
}
